package com.example.auv_660.moduleload;

import com.example.auv_660.MainActivity;
import com.example.auv_660.network.tcp.ModuleReadHandler;
import com.example.auv_660.network.tcp.ModuleWriteHandler;
import com.example.auv_660.util.Constants;
import com.example.auv_660.util.MsgType;
import com.example.auv_660.util.ThreadPool;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.ArrayList;
import java.util.TimerTask;

public class DepthSensorLoad extends ModuleLoad {
    // 回车换行
    private static final String DEPTHSENSOR_TIME_TASK = "$Ask,Depth*\r\n";
    public static ModuleWriteHandler depthSensorWriteHandler;
    private ModuleReadHandler depthSensorReadHandler;
    private AsynchronousSocketChannel asynchronousSocketChannel;
    private double depthAC = 1000;
    private double DepthAdj = 9.28;     // 水面深度调整
    private MainActivity mainActivity = MainActivity.getInstance();
    private int threadKey = 0;
    private ArrayList<Double> list = new ArrayList<Double>();
    private static int count = 0;

    private boolean checkBasement = false;

    public DepthSensorLoad() throws IOException
    {

    }

    @Override
    public void doModuleLoad(String remoteModuleIP, AsynchronousSocketChannel asynchronousSocketChannel) {
        if (remoteModuleIP.equals(Constants.DEPTH_SENSOR_IP))
        {
            if (this.asynchronousSocketChannel != null)
            {
                releaseModuleResource();
            }

            this.asynchronousSocketChannel = asynchronousSocketChannel;

            if (depthSensorWriteHandler == null)
            {
                depthSensorWriteHandler = new ModuleWriteHandler(asynchronousSocketChannel);
            }

            if (depthSensorReadHandler == null)
            {
                depthSensorReadHandler = new ModuleReadHandler(asynchronousSocketChannel)
                {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment)
                    {
                        if (result > 0)
                        {
                            attachment.flip();
                            byte[] bytes = new byte[attachment.remaining()];
                            attachment.get(bytes);

                            String str = new String(bytes);
                            String depthValue = null;
                            depthAC = 1000;

                            if (!str.contains("Error"))
                            {
                                depthValue = str.split(",")[2].split("\\*")[0];
                                double valueTmp = - Double.parseDouble(depthValue.split("\\+")[1]);
                                depthAC = valueTmp + DepthAdj;

                                if (checkBasement)
                                {
                                    list.add(valueTmp);
                                    System.out.println("list size: " + list.size());
                                    if (list.size() == 10)
                                    {
                                        double tmp = 0.0;
                                        for (double value : list)
                                        {
                                            tmp += -value;
                                        }
                                        DepthAdj = tmp / 10.0;
                                        checkBasement = false;
                                        System.out.println("checkBasement1: " + checkBasement);
                                        list.clear();
                                        list = new ArrayList<Double>();
                                    }
                                }
                            }
                            else
                            {
                                depthValue = str;
                            }

                            if (mainActivity != null)
                            {
                                mainActivity.sendMsgToMainThread(MsgType.DEPTH_SENSOR_MSG, depthValue);
                            }
                            getMessageFromModule();
                        }
                    }
                };
                depthSensorReadHandler.getMessageFromModule();
            }

            try
            {
                if (mainActivity != null && asynchronousSocketChannel != null)
                {
                    String ip = asynchronousSocketChannel.getRemoteAddress().toString();
                    mainActivity.sendMsgToMainThread(MsgType.DEPTH_SENSOR_CONN, ip.split("/")[1]);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

            if (depthSensorWriteHandler == null)
            {
                if (mainActivity != null)
                {
                    mainActivity.sendMsgToMainThread(MsgType.DEPTH_SENSOR_CONN, "失去连接");
                }
            }
            else
            {
                if (threadKey != 0)
                {
                    ThreadPool.INSTANCE.getThreadPoolProxy().shutDownScheduledTask(threadKey);
                }

                threadKey = ThreadPool.INSTANCE.getThreadPoolProxy().scheduledTask(new TimerTask() {
                    @Override
                    public void run() {
                        depthSensorWriteHandler.sendCommandToModule(DEPTHSENSOR_TIME_TASK);
                    }
                }, 1000);
            }

            return;
        }
        else
        {
            ModuleLoad nextModule = this.getNextModule();
            if (nextModule != null)
            {
                nextModule.doModuleLoad(remoteModuleIP, asynchronousSocketChannel);
            }
        }
    }

    @Override
    public ModuleWriteHandler getWriterHandler() {
        if (depthSensorWriteHandler == null)
        {
            if (mainActivity != null)
            {
                mainActivity.sendMsgToMainThread(MsgType.TOAST_MSG, "深度传感器未连接");
            }
        }
        return depthSensorWriteHandler;
    }

    @Override
    public ModuleReadHandler getReadHandler() {
        if (depthSensorReadHandler == null)
        {
            if (mainActivity != null)
            {
                mainActivity.sendMsgToMainThread(MsgType.TOAST_MSG, "深度传感器未连接");
            }
        }
        return depthSensorReadHandler;
    }

    @Override
    public void releaseModuleResource() {
        if (depthSensorReadHandler != null)
        {
            depthSensorReadHandler = null;
        }
        if (depthSensorWriteHandler != null)
        {
            depthSensorWriteHandler = null;
        }
        if (this.asynchronousSocketChannel != null)
        {
            try
            {
                this.asynchronousSocketChannel.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        ThreadPool.INSTANCE.getThreadPoolProxy().shutDownScheduledTask(threadKey);
    }

    public double getDepthAC()
    {
        return depthAC;
    }

    public boolean fixBasement()
    {
        checkBasement = true;

        while (checkBasement)
        {
            try
            {
                Thread.sleep(100);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        System.out.println("checkBasement: " + checkBasement);
        return !checkBasement;
    }
}


